package com.ywk.json.process;


import com.ywk.json.core.IOutPut;
import com.ywk.json.entity.User;
import com.ywk.json.utils.JsonUtil;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zbh
 * @date 2022/3/8 18:11
 */
public class JsonProcess {

    List<User> contentList =new ArrayList();

    private List<IOutPut> outPutsHandlers=new ArrayList<>();

    public void parse(String path) {
        //解析json文件
        String content = readFile(path);
        contentList = JsonUtil.jsonToList(content,User.class);
        contentList.forEach(System.out::println);
    }

    private String readFile(String path) {
        StringBuffer jsonStr=new StringBuffer();
        try {
            List<String> list = Files.readAllLines(Paths.get(path));
            list.forEach(s -> jsonStr.append(s));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonStr.toString();
    }

    public JsonProcess addOutPutHandler(IOutPut outPutHandler){
        outPutsHandlers.add(outPutHandler);
        return this;
    }

    public void outPut() {
        for (IOutPut outPutsHandler : outPutsHandlers) {
            outPutsHandler.outPut(contentList);
        }
    }

}
